<?php
class HttpClient
{
    /**
     * @desc   curl
     *
     * @param  $url
     * @param  $data
     * @param  $head
     *
     * @return array
     * @author yzf
     * @date   2021/8/18 5:57 下午
     */
    public static function httpRequest($url, $data = null, $head = '')
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if ( !empty($data) ) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        if ( !empty($head) ) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $head);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        // 接口异常
        if ($httpCode != 200 || empty($output)) {
            return [];
        }
        $data = json_decode($output, true, JSON_UNESCAPED_UNICODE);
        // 返回数据格式异常
        if(json_last_error()){
            return [];
        }
        return  $data;
    }
    /**
     * @desc   生成签名
     *
     * @param  $urlPath
     * @param  $data_post
     *
     * @return
     * @author yzf
     * @date   2021/8/18 6:06 下午
     */
    public static function createSn($urlPath, $dataPost, $secret, $appId)
    {
        $dataGet   = [
            'appid' => $appId,
            'timestamp' => time()
        ];

        //合并参数
        $params = array_merge($dataPost, $dataGet, array('path' => strtolower($urlPath)));
        ksort($params);
        $item = array();
        foreach($params as $k => $v){
            if(is_array($v)){
                $v = json_encode($v);
            }
            $item[] = "$k=$v";
        }
        $signStr = implode('&', $item) . '&secretkey=' . $secret;
        print_r($signStr);
        $sn = md5(md5($signStr));
        return array_merge($dataGet, ['sn' => $sn]);
    }
}